package com.foxit.pdf2pdf.web.common;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.log4j.Logger;

public class TFSFileUntil {
	
	private static final Logger log = Logger.getLogger(TFSFileUntil.class);
	
	public static boolean saveContent(String patch,byte data[]) throws Exception{
		//log.debug(patch + " saveContent start");
        // Post请求的url，与get不同的是不需要带参数
        URL postUrl = null;
		try {
			postUrl = new URL(patch);
		} catch (MalformedURLException e) {
			log.error(patch +": The path is incorrect");
			return false;
		}
        // 打开连接
        HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) postUrl
			        .openConnection();
		} catch (IOException e) {
			log.error("Failed to open an TFS connection");
			return false;
		}
        // Output to the connection. Default is
        // false, set to true because post
        // method must write something to the
        // connection
        // 设置是否向connection输出，因为这个是post请求，参数要放在
        // http正文内，因此需要设为true
        connection.setDoOutput(true);
        // Read from the connection. Default is true.
        connection.setDoInput(true);
        // Set the post method. Default is GET
        try {
			connection.setRequestMethod("PUT");
		} catch (ProtocolException e) {
			log.error(e.getMessage());
			return false;
		}
        // Post cannot use caches
        // Post 请求不能使用缓存
        connection.setUseCaches(false);
        // Set the content type to urlencoded,
        // because we will write
        // some URL-encoded content to the
        // connection. Settings above must be set before connect!
        // 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
        // 意思是正文是urlencoded编码过的form参数，下面我们可以看到我们对正文内容使用URLEncoder.encode
        // 进行编码
        connection.setRequestProperty("Content-Type",
                "application/octet-stream");
        final int _SIZE = data.length;
        connection.setRequestProperty("Content-Length", "" + _SIZE);
        connection.setFixedLengthStreamingMode(_SIZE);
        connection.setConnectTimeout(30000);   
		connection.setReadTimeout(30000);
        //connection.setRequestProperty("Transfer-Encoding", "chunked");
        // 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
        // 要注意的是connection.getOutputStream会隐含的进行connect。
        try {
			connection.connect();
			//log.debug("connect....");
		} catch (IOException e) {
			log.error(e.getMessage());
			return false;
		}
        DataOutputStream out = null;
		try {
			out = new DataOutputStream(connection
			        .getOutputStream());
		} catch (IOException e) {
			log.error(e.getMessage());
			return false;
		}
        try {
			out.write(data);
		} catch (IOException e) {
			log.error(e.getMessage());
			return false;
		}

        try {
			out.close(); // flush and close
		} catch (IOException e) {
			log.error(e.getMessage());
			return false;
		}
        //提示知道新文件的URL 201
        int retCode = connection.getResponseCode();
        //log.debug("retCode:" + retCode);
        if(retCode != HttpStatus.SC_CREATED ){
        	log.error("save data to tfs failed,http code:"+ retCode+", url:"+patch);
        	return false;
        };
        
        //log.debug(patch + " saveContent end");
        return true;
    }
	
	public static InputStream readerContent(String path){
		URL getUrl = null;
		//log.debug("Get cache from:"+path);
		try {
			getUrl = new URL(path);
		} catch (MalformedURLException e) {
			log.error(path +": The path is incorrect");
			return null;
		}
        // 打开连接
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) getUrl
			        .openConnection();
		} catch (IOException e) {
			log.error("Failed to open an TFS connection");
			return null;
		}
        
        try {
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(30000);   
			connection.setReadTimeout(30000);
		} catch (ProtocolException e) {
			log.error(e);
			return null;
		}
		
		InputStream inputstream = null;
		try {
			inputstream = connection.getInputStream();
		} catch (IOException e) {
			log.error("Failed to read data at TFS",e);
			return null;
		}
        return inputstream;
	}
	
	//删除TFS 上的数据
	public static boolean removeContent(String patch){
		URL getUrl = null;
		try {
			getUrl = new URL(patch);
		} catch (MalformedURLException e) {
			log.error(patch +": The path is not correct");
			return false;
		}
        // 打开连接
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) getUrl
			        .openConnection();
		} catch (IOException e) {
			log.error("Failed to open an TFS connection",e);
			return false;
		}
        
        try {
			connection.setRequestMethod("DELETE");
			connection.setConnectTimeout(30000);   
		} catch (ProtocolException e) {
			log.error(e);
			return false;
		}
		try {
			connection.connect();
			int code = connection.getResponseCode();
			//connection.getResponseCode() 必须有 不难tfs 上数据删除不掉
			log.info("response code:"+code);
			return true;
		} catch (IOException e) {
			log.error("Failed to delete the TFS(patch="+patch+") data",e);
			return false;
		}
	}
}
